

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="深海火锅店">
  <meta name="keywords" content="">
  
    <meta name="description" content="Redux介绍Redux是React中使用广泛的集中状态管理工具  类比vuex之于vue 同类的工具还有mobx等  为什么要使用Redux？  独立于组件，无视组件之间的层级关系，简化通信问题 单项数据流清晰，易于定位bug 调试工具配套良好，方便调试  Redux快速体验1. Redux数据流架构Redux的难点是理解它对于数据修改的规则, 下图动态展示了在整个数据的修改中，数据的流向  为">
<meta property="og:type" content="article">
<meta property="og:title" content="04.Redux">
<meta property="og:url" content="http://example.com/2023/06/04/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/React/04.Redux/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="Redux介绍Redux是React中使用广泛的集中状态管理工具  类比vuex之于vue 同类的工具还有mobx等  为什么要使用Redux？  独立于组件，无视组件之间的层级关系，简化通信问题 单项数据流清晰，易于定位bug 调试工具配套良好，方便调试  Redux快速体验1. Redux数据流架构Redux的难点是理解它对于数据修改的规则, 下图动态展示了在整个数据的修改中，数据的流向  为">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://gitee.com/tongstyle/markdown-img/raw/master/202307132139731.png">
<meta property="og:image" content="https://gitee.com/tongstyle/markdown-img/raw/master/202307132139992.png">
<meta property="og:image" content="https://gitee.com/tongstyle/markdown-img/raw/master/202307132140463.png">
<meta property="article:published_time" content="2023-06-03T16:00:00.000Z">
<meta property="article:modified_time" content="2024-02-15T16:05:05.729Z">
<meta property="article:author" content="深海火锅店">
<meta property="article:tag" content="React">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:image" content="https://gitee.com/tongstyle/markdown-img/raw/master/202307132139731.png">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>04.Redux - Hexo</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"example.com","root":"/","version":"1.9.3","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"right","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 70vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Fluid</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/background.jpg') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="04.Redux"></span>
          
        </div>

        
          
  <div class="mt-3">
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2023-06-04 00:00" pubdate>
          2023年6月4日 凌晨
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          10k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          84 分钟
        
      </span>
    

    
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">04.Redux</h1>
            
            
              <div class="markdown-body">
                
                <h1 id="Redux介绍"><a href="#Redux介绍" class="headerlink" title="Redux介绍"></a>Redux介绍</h1><p>Redux是React中使用广泛的集中状态管理工具  类比vuex之于vue 同类的工具还有mobx等</p>
<p><img src="https://gitee.com/tongstyle/markdown-img/raw/master/202307132139731.png" srcset="/img/loading.gif" lazyload alt="img"></p>
<p><strong>为什么要使用Redux？</strong></p>
<ol>
<li>独立于组件，无视组件之间的层级关系，简化通信问题</li>
<li>单项数据流清晰，易于定位bug</li>
<li>调试工具配套良好，方便调试</li>
</ol>
<h1 id="Redux快速体验"><a href="#Redux快速体验" class="headerlink" title="Redux快速体验"></a>Redux快速体验</h1><h2 id="1-Redux数据流架构"><a href="#1-Redux数据流架构" class="headerlink" title="1. Redux数据流架构"></a>1. Redux数据流架构</h2><p>Redux的难点是理解它对于数据修改的规则, 下图动态展示了在整个数据的修改中，数据的流向</p>
<p><img src="https://gitee.com/tongstyle/markdown-img/raw/master/202307132139992.png" srcset="/img/loading.gif" lazyload alt="img"></p>
<p>为了职责清晰，Redux代码被分为三个核心的概念，我们学redux，其实就是学这三个核心概念之间的配合，三个概念分别是:</p>
<ol>
<li>state:  一个对象 存放着我们管理的数据</li>
<li>action:  一个对象 用来描述你想怎么改数据</li>
<li>reducer:  一个函数 根据action的描述更新state</li>
</ol>
<h2 id="2-纯Redux实现计数器"><a href="#2-纯Redux实现计数器" class="headerlink" title="2. 纯Redux实现计数器"></a>2. 纯Redux实现计数器</h2><p>核心步骤</p>
<ol>
<li>创建reducer函数 在内部定义好action和state的定义关系</li>
<li>调用Redux的createStore方法传入定义好的reducer函数生成store实例</li>
<li>通过store实例身上的subscribe方法监控数据是否变化</li>
<li>点击按钮 通过专门的dispatch函数 提交action对象 实现数据更新</li>
</ol>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><code class="hljs html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;decrement&quot;</span>&gt;</span>-<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;count&quot;</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><br><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">&quot;increment&quot;</span>&gt;</span>+<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span><br><br><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">&quot;https://unpkg.com/redux@latest/dist/redux.min.js&quot;</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br><br><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="language-javascript"></span><br><span class="language-javascript">  <span class="hljs-comment">// 定义reducer函数 </span></span><br><span class="language-javascript">  <span class="hljs-comment">// 内部主要的工作是根据不同的action 返回不同的state</span></span><br><span class="language-javascript">  <span class="hljs-keyword">function</span> <span class="hljs-title function_">counterReducer</span> (state = &#123; <span class="hljs-attr">count</span>: <span class="hljs-number">0</span> &#125;, action) &#123;</span><br><span class="language-javascript">    <span class="hljs-keyword">switch</span> (action.<span class="hljs-property">type</span>) &#123;</span><br><span class="language-javascript">      <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;INCREMENT&#x27;</span>:</span><br><span class="language-javascript">        <span class="hljs-keyword">return</span> &#123; <span class="hljs-attr">count</span>: state.<span class="hljs-property">count</span> + <span class="hljs-number">1</span> &#125;</span><br><span class="language-javascript">      <span class="hljs-keyword">case</span> <span class="hljs-string">&#x27;DECREMENT&#x27;</span>:</span><br><span class="language-javascript">        <span class="hljs-keyword">return</span> &#123; <span class="hljs-attr">count</span>: state.<span class="hljs-property">count</span> - <span class="hljs-number">1</span> &#125;</span><br><span class="language-javascript">      <span class="hljs-attr">default</span>:</span><br><span class="language-javascript">        <span class="hljs-keyword">return</span> state</span><br><span class="language-javascript">    &#125;</span><br><span class="language-javascript">  &#125;</span><br><span class="language-javascript">  <span class="hljs-comment">// 使用reducer函数生成store实例</span></span><br><span class="language-javascript">  <span class="hljs-keyword">const</span> store = <span class="hljs-title class_">Redux</span>.<span class="hljs-title function_">createStore</span>(counterReducer)</span><br><span class="language-javascript">  </span><br><span class="language-javascript">  <span class="hljs-comment">// 订阅数据变化</span></span><br><span class="language-javascript">  store.<span class="hljs-title function_">subscribe</span>(<span class="hljs-function">() =&gt;</span> &#123;</span><br><span class="language-javascript">    <span class="hljs-variable language_">console</span>.<span class="hljs-title function_">log</span>(store.<span class="hljs-title function_">getState</span>())</span><br><span class="language-javascript">    <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;count&#x27;</span>).<span class="hljs-property">innerText</span> = store.<span class="hljs-title function_">getState</span>().<span class="hljs-property">count</span></span><br><span class="language-javascript">    </span><br><span class="language-javascript">  &#125;)</span><br><span class="language-javascript">  <span class="hljs-comment">// 增</span></span><br><span class="language-javascript">  <span class="hljs-keyword">const</span> inBtn = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;increment&#x27;</span>)</span><br><span class="language-javascript">  inBtn.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function">() =&gt;</span> &#123;</span><br><span class="language-javascript">    store.<span class="hljs-title function_">dispatch</span>(&#123;</span><br><span class="language-javascript">      <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;INCREMENT&#x27;</span></span><br><span class="language-javascript">    &#125;)</span><br><span class="language-javascript">  &#125;)</span><br><span class="language-javascript">  <span class="hljs-comment">// 减</span></span><br><span class="language-javascript">  <span class="hljs-keyword">const</span> dBtn = <span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;decrement&#x27;</span>)</span><br><span class="language-javascript">  dBtn.<span class="hljs-title function_">addEventListener</span>(<span class="hljs-string">&#x27;click&#x27;</span>, <span class="hljs-function">() =&gt;</span> &#123;</span><br><span class="language-javascript">    store.<span class="hljs-title function_">dispatch</span>(&#123;</span><br><span class="language-javascript">      <span class="hljs-attr">type</span>: <span class="hljs-string">&#x27;DECREMENT&#x27;</span></span><br><span class="language-javascript">    &#125;)</span><br><span class="language-javascript">  &#125;)</span><br><span class="language-javascript"></span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span><br></code></pre></td></tr></table></figure>

<h1 id="Redux与React"><a href="#Redux与React" class="headerlink" title="Redux与React"></a>Redux与React</h1><p>Redux虽然是一个框架无关可以独立运行的插件，但是社区通常还是把它与React绑定在一起使用，以一个计数器案例体验一下Redux + React 的基础使用</p>
<h2 id="1-开发环境准备"><a href="#1-开发环境准备" class="headerlink" title="1. 开发环境准备"></a>1. 开发环境准备</h2><p>使用create-react-app创建react基础项目，并安装Redux相关工具</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment"># 创建项目</span><br>$ yarn create vite react-redux --template react<br><br><br><span class="hljs-comment"># 安装redux配套工具</span><br>$ yarn add  @reduxjs/toolkit react-redux<br><br><span class="hljs-comment"># 启动项目</span><br>$ yarn dev<br></code></pre></td></tr></table></figure>

<p>目录核心结构</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs plain">src<br>  - store<br>    - modules  // 模块store<br>    - index.js // 组合模块的入口文件<br>  - App.js<br></code></pre></td></tr></table></figure>

<h2 id="2-创建counterStore"><a href="#2-创建counterStore" class="headerlink" title="2. 创建counterStore"></a>2. 创建counterStore</h2><p>创建store的的核心步骤分为两步</p>
<ol>
<li>使用toolkit的<strong>createSlice</strong>方法创建一个独立的子模块</li>
<li>使用<strong>configureStore</strong>语法组合子模块</li>
</ol>
<p>1- 创建子模块</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; createSlice &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@reduxjs/toolkit&#x27;</span><br><br><span class="hljs-keyword">const</span> counter = <span class="hljs-title function_">createSlice</span>(&#123;<br>  <span class="hljs-comment">// 模块名称独一无二</span><br>  <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;counter&#x27;</span>,<br>  <span class="hljs-comment">// 初始数据</span><br>  <span class="hljs-attr">initialState</span>: &#123;<br>    <span class="hljs-attr">count</span>: <span class="hljs-number">1</span><br>  &#125;,<br>  <span class="hljs-comment">// 修改数据的同步方法</span><br>  <span class="hljs-attr">reducers</span>: &#123;<br>    add (state) &#123;<br>      state.<span class="hljs-property">count</span>++<br>    &#125;<br>  &#125;<br>&#125;)<br><br><span class="hljs-keyword">const</span> &#123; add &#125; = counter.<span class="hljs-property">actions</span><br><span class="hljs-keyword">const</span> counterReducer = counter.<span class="hljs-property">reducer</span><br><br><span class="hljs-comment">// 导出修改数据的函数</span><br><span class="hljs-keyword">export</span> &#123; add &#125;<br><span class="hljs-comment">// 导出reducer</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> counterReducer<br></code></pre></td></tr></table></figure>

<p>2- 组合子模块</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; configureStore &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@reduxjs/toolkit&#x27;</span><br><br><span class="hljs-keyword">import</span> counterReducer <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./counterStore&#x27;</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title function_">configureStore</span>(&#123;<br>  <span class="hljs-attr">reducer</span>: &#123;<br>    <span class="hljs-comment">// 注册子模块</span><br>    <span class="hljs-attr">counter</span>: counterReducer<br>  &#125;<br>&#125;)<br></code></pre></td></tr></table></figure>

<h2 id="3-为React提供Redux-store"><a href="#3-为React提供Redux-store" class="headerlink" title="3. 为React提供Redux store"></a>3. 为React提供Redux store</h2><p>要想让所有的组件都有资格访问store中的数据，需要我们在入口文件中，渲染根组件的位置通过Provider提供store数据</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs jsx"><span class="hljs-keyword">import</span> <span class="hljs-title class_">React</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">ReactDOM</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react-dom/client&#x27;</span><br><span class="hljs-keyword">import</span> <span class="hljs-title class_">App</span> <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./App&#x27;</span><br><span class="hljs-comment">// 导入store</span><br><span class="hljs-keyword">import</span> store <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./store&#x27;</span><br><span class="hljs-comment">// 导入store提供组件Provider</span><br><span class="hljs-keyword">import</span> &#123; <span class="hljs-title class_">Provider</span> &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react-redux&#x27;</span><br><br><span class="hljs-title class_">ReactDOM</span>.<span class="hljs-title function_">createRoot</span>(<span class="hljs-variable language_">document</span>.<span class="hljs-title function_">getElementById</span>(<span class="hljs-string">&#x27;root&#x27;</span>)).<span class="hljs-title function_">render</span>(<br>  <span class="hljs-comment">// 提供store数据</span><br>  <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">Provider</span> <span class="hljs-attr">store</span>=<span class="hljs-string">&#123;store&#125;</span>&gt;</span></span><br><span class="language-xml">    <span class="hljs-tag">&lt;<span class="hljs-name">App</span> /&gt;</span></span><br><span class="language-xml">  <span class="hljs-tag">&lt;/<span class="hljs-name">Provider</span>&gt;</span></span><br>)<br></code></pre></td></tr></table></figure>

<h2 id="4-组件使用store中的数据"><a href="#4-组件使用store中的数据" class="headerlink" title="4. 组件使用store中的数据"></a>4. 组件使用store中的数据</h2><p>组件使用store中的数据需要借助一个hook方法，叫做useSelector</p>
<p>useSelector(state &#x3D;&gt; state.模块名)  方法的返回值为一个对象，对象中包含store子模块中的所有数据</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><code class="hljs jsx"><span class="hljs-keyword">import</span> &#123; useSelector &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react-redux&#x27;</span><br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">App</span> () &#123;<br>  <span class="hljs-comment">// 使用数据</span><br>  <span class="hljs-keyword">const</span> &#123; count &#125; = <span class="hljs-title function_">useSelector</span>(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.<span class="hljs-property">counter</span>)<br>  <br>  <span class="hljs-keyword">return</span> (<br>    <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">&quot;App&quot;</span>&gt;</span></span><br><span class="language-xml">      &#123;count&#125;</span><br><span class="language-xml">      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">&#123;clickHandler&#125;</span>&gt;</span>+<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span><br><span class="language-xml">    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br>  )<br>&#125;<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">App</span><br></code></pre></td></tr></table></figure>



<h2 id="5-组件修改store中的数据"><a href="#5-组件修改store中的数据" class="headerlink" title="5. 组件修改store中的数据"></a>5. 组件修改store中的数据</h2><p>修改store中的数据有俩个核心步骤</p>
<ol>
<li>使用counterStore模块中导出的add方法创建action对象</li>
<li>通过dispatch函数以action作为参数传入完成数据更新</li>
</ol>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><code class="hljs jsx"><span class="hljs-keyword">import</span> &#123; useSelector, useDispatch &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react-redux&#x27;</span><br><span class="hljs-keyword">import</span> &#123; add &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./store/counterStore&#x27;</span><br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">App</span> () &#123;<br>  <span class="hljs-comment">// 使用数据</span><br>  <span class="hljs-keyword">const</span> &#123; count &#125; = <span class="hljs-title function_">useSelector</span>(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.<span class="hljs-property">counter</span>)<br>  <span class="hljs-comment">// 修改数据</span><br>  <span class="hljs-keyword">const</span> dispatch = <span class="hljs-title function_">useDispatch</span>()<br>  <span class="hljs-keyword">const</span> <span class="hljs-title function_">clickHandler</span> = (<span class="hljs-params"></span>) =&gt; &#123;<br>    <span class="hljs-comment">// 1. 生成action对象</span><br>    <span class="hljs-keyword">const</span> action = <span class="hljs-title function_">add</span>()<br>    <span class="hljs-comment">// 2. 提交action进行数据更新</span><br>    <span class="hljs-title function_">dispatch</span>(action)<br>  &#125;<br>  <span class="hljs-keyword">return</span> (<br>    <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">&quot;App&quot;</span>&gt;</span></span><br><span class="language-xml">      &#123;count&#125;</span><br><span class="language-xml">      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">&#123;clickHandler&#125;</span>&gt;</span>+<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span><br><span class="language-xml">    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br>  )<br>&#125;<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">App</span><br></code></pre></td></tr></table></figure>



<h2 id="6-组件修改数据并传参"><a href="#6-组件修改数据并传参" class="headerlink" title="6. 组件修改数据并传参"></a>6. 组件修改数据并传参</h2><p>上一小节通过dispatch函数提交action修改了数据，如果在提交的时候需要传参怎么做呢</p>
<p>1- 修改数据的方法中补充第二个参数action</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; createSlice &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&quot;@reduxjs/toolkit&quot;</span><br><span class="hljs-keyword">const</span> counterStore = <span class="hljs-title function_">createSlice</span>(&#123;<br>  <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;counter&#x27;</span>, <span class="hljs-comment">// 独一无二不重复的名字语义化</span><br>  <span class="hljs-comment">// 定义初始化的数据</span><br>  <span class="hljs-attr">initialState</span>: &#123;<br>    <span class="hljs-attr">taskList</span>: [<span class="hljs-string">&#x27;react&#x27;</span>]<br>  &#125;,<br>  <span class="hljs-attr">reducers</span>: &#123;<br>    <span class="hljs-comment">// action为一个对象 对象中有一个固定的属性叫做payload 为传递过来的参数</span><br>    addTaskList (state, action) &#123;<br>      state.<span class="hljs-property">taskList</span>.<span class="hljs-title function_">push</span>(action.<span class="hljs-property">payload</span>)<br>    &#125;<br>  &#125;<br>&#125;)<br><br><span class="hljs-comment">// 生成修改数据的方法导出</span><br><span class="hljs-keyword">const</span> &#123; addTaskList &#125; = counterStore.<span class="hljs-property">actions</span><br><span class="hljs-keyword">export</span> &#123; addTaskList &#125;<br><span class="hljs-comment">// 生成reducer 导出 供index.js做组合模块</span><br><span class="hljs-keyword">const</span> counterReducer = counterStore.<span class="hljs-property">reducer</span><br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> counterReducer<br></code></pre></td></tr></table></figure>

<p>2- dispatch的时候传入实参</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><code class="hljs jsx">&lt;button onClick=&#123;<span class="hljs-function">() =&gt;</span> <span class="hljs-title function_">dispatch</span>(<span class="hljs-title function_">addTaskList</span>(<span class="hljs-string">&#x27;vue&#x27;</span>))&#125;&gt;addList&lt;/button&gt;<br></code></pre></td></tr></table></figure>

<h2 id="7-Redux异步处理"><a href="#7-Redux异步处理" class="headerlink" title="7. Redux异步处理"></a>7. Redux异步处理</h2><p>测试接口地址：  <a target="_blank" rel="noopener" href="http://geek.itheima.net/v1_0/channels'">http://geek.itheima.net/v1_0&#x2F;channels</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-keyword">import</span> &#123; createSlice &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@reduxjs/toolkit&#x27;</span><br><span class="hljs-keyword">import</span> axios <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;axios&#x27;</span><br><br><span class="hljs-keyword">const</span> channelStore = <span class="hljs-title function_">createSlice</span>(&#123;<br>  <span class="hljs-attr">name</span>: <span class="hljs-string">&#x27;channel&#x27;</span>,<br>  <span class="hljs-attr">initialState</span>: &#123;<br>    <span class="hljs-attr">channelList</span>: []<br>  &#125;,<br>  <span class="hljs-attr">reducers</span>: &#123;<br>    setChannelList (state, action) &#123;<br>      state.<span class="hljs-property">channelList</span> = action.<span class="hljs-property">payload</span><br>    &#125;<br>  &#125;<br>&#125;)<br><br><br><span class="hljs-comment">// 创建异步</span><br><span class="hljs-keyword">const</span> &#123; setChannelList &#125; = channelStore.<span class="hljs-property">actions</span><br><span class="hljs-keyword">const</span> url = <span class="hljs-string">&#x27;http://geek.itheima.net/v1_0/channels&#x27;</span><br><span class="hljs-comment">// 封装一个函数 在函数中return一个新函数 在新函数中封装异步</span><br><span class="hljs-comment">// 得到数据之后通过dispatch函数 触发修改</span><br><span class="hljs-keyword">const</span> <span class="hljs-title function_">fetchChannelList</span> = (<span class="hljs-params"></span>) =&gt; &#123;<br>  <span class="hljs-keyword">return</span> <span class="hljs-keyword">async</span> (dispatch) =&gt; &#123;<br>    <span class="hljs-keyword">const</span> res = <span class="hljs-keyword">await</span> axios.<span class="hljs-title function_">get</span>(url)<br>    <span class="hljs-title function_">dispatch</span>(<span class="hljs-title function_">setChannelList</span>(res.<span class="hljs-property">data</span>.<span class="hljs-property">data</span>.<span class="hljs-property">channels</span>))<br>  &#125;<br>&#125;<br><br><span class="hljs-keyword">export</span> &#123; fetchChannelList &#125;<br><br><span class="hljs-keyword">const</span> channelReducer = channelStore.<span class="hljs-property">reducer</span><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> channelReducer<br><span class="hljs-keyword">import</span> &#123; useEffect &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react&#x27;</span><br><span class="hljs-keyword">import</span> &#123; useSelector, useDispatch &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react-redux&#x27;</span><br><span class="hljs-keyword">import</span> &#123; fetchChannelList &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;./store/channelStore&#x27;</span><br><br><span class="hljs-keyword">function</span> <span class="hljs-title function_">App</span> () &#123;<br>  <span class="hljs-comment">// 使用数据</span><br>  <span class="hljs-keyword">const</span> &#123; channelList &#125; = <span class="hljs-title function_">useSelector</span>(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.<span class="hljs-property">channel</span>)<br>  <span class="hljs-title function_">useEffect</span>(<span class="hljs-function">() =&gt;</span> &#123;<br>    <span class="hljs-title function_">dispatch</span>(<span class="hljs-title function_">fetchChannelList</span>())<br>  &#125;, [dispatch])<br><br>  <span class="hljs-keyword">return</span> (<br>    <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">&quot;App&quot;</span>&gt;</span></span><br><span class="language-xml">      <span class="hljs-tag">&lt;<span class="hljs-name">ul</span>&gt;</span></span><br><span class="language-xml">        &#123;channelList.map(task =&gt; <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&#123;task.id&#125;</span>&gt;</span>&#123;task.name&#125;<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>)&#125;</span><br><span class="language-xml">      <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span><br><span class="language-xml">    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br>  )<br>&#125;<br><br><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-title class_">App</span><br></code></pre></td></tr></table></figure>



<h1 id="Todos综合案例"><a href="#Todos综合案例" class="headerlink" title="Todos综合案例"></a>Todos综合案例</h1><p><img src="https://gitee.com/tongstyle/markdown-img/raw/master/202307132140463.png" srcset="/img/loading.gif" lazyload alt="img"></p>
<h2 id="1-准备开发环境"><a href="#1-准备开发环境" class="headerlink" title="1. 准备开发环境"></a>1. 准备开发环境</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment"># 克隆项目到本地</span><br>$ git <span class="hljs-built_in">clone</span> https://gitee.com/react-course-series/react-redux.git<br><br><span class="hljs-comment"># 安装所有依赖</span><br><br>$ yarn <br><span class="hljs-comment"># or </span><br>$ npm i<br></code></pre></td></tr></table></figure>

<h2 id="2-渲染列表"><a href="#2-渲染列表" class="headerlink" title="2. 渲染列表"></a>2. 渲染列表</h2><ol>
<li>在组件中通过核心方法 useSelector方法使用数据</li>
<li>使用map方法进行列表遍历</li>
</ol>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs jsx"><span class="hljs-comment">// 导入useSelector方法</span><br><span class="hljs-keyword">import</span> &#123; useSelector &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react-redux&#x27;</span><br><br><span class="hljs-comment">// 从store中获取list数据</span><br><span class="hljs-keyword">const</span> &#123; list &#125; = <span class="hljs-title function_">useSelector</span>(<span class="hljs-function"><span class="hljs-params">state</span> =&gt;</span> state.<span class="hljs-property">taskStore</span>)<br><br><br><span class="hljs-comment">// 渲染列表</span><br>&lt;ul className=<span class="hljs-string">&quot;todo-list&quot;</span>&gt;<br>  &#123;list.<span class="hljs-title function_">map</span>(<span class="hljs-function">(<span class="hljs-params">task</span>) =&gt;</span> (<br>    <span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">&#123;task.id&#125;</span> <span class="hljs-attr">className</span>=<span class="hljs-string">&#123;task.done</span> ? &#x27;<span class="hljs-attr">completed</span> <span class="hljs-attr">todo</span>&#x27; <span class="hljs-attr">:</span> &#x27;<span class="hljs-attr">todo</span>&#x27;&#125;&gt;</span></span><br><span class="language-xml">      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">&quot;view&quot;</span>&gt;</span></span><br><span class="language-xml">        <span class="hljs-tag">&lt;<span class="hljs-name">input</span></span></span><br><span class="hljs-tag"><span class="language-xml">          <span class="hljs-attr">className</span>=<span class="hljs-string">&quot;toggle&quot;</span></span></span><br><span class="hljs-tag"><span class="language-xml">          <span class="hljs-attr">type</span>=<span class="hljs-string">&quot;checkbox&quot;</span></span></span><br><span class="hljs-tag"><span class="language-xml">          <span class="hljs-attr">checked</span>=<span class="hljs-string">&#123;task.done&#125;</span></span></span><br><span class="hljs-tag"><span class="language-xml">          <span class="hljs-attr">onChange</span>=<span class="hljs-string">&#123;(e)</span> =&gt;</span> singleCheck(task.id, e)&#125;</span><br><span class="language-xml">        /&gt;</span><br><span class="language-xml">        <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span> &#123;task.title&#125; <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span></span><br><span class="language-xml">        <span class="hljs-tag">&lt;<span class="hljs-name">button</span></span></span><br><span class="hljs-tag"><span class="language-xml">          <span class="hljs-attr">className</span>=<span class="hljs-string">&quot;destroy&quot;</span></span></span><br><span class="hljs-tag"><span class="language-xml">          <span class="hljs-attr">onClick</span>=<span class="hljs-string">&#123;()</span> =&gt;</span> delTask(task.id)&#125;&gt;<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span><br><span class="language-xml">      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span><br><span class="language-xml">    <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span><br>  ))&#125;<br>&lt;/ul&gt;<br></code></pre></td></tr></table></figure>

<h2 id="3-实现删除"><a href="#3-实现删除" class="headerlink" title="3. 实现删除"></a>3. 实现删除</h2><p>实现步骤：</p>
<ol>
<li>在store的reducers选项中定义修改数据的方法 然后导出</li>
<li>在组件中通过dispatch函数触发方法的执行并传入id参数</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-attr">reducers</span>:&#123;<br>  <span class="hljs-comment">// 删除的方法</span><br>   delTask (state, action) &#123;<br>      state.<span class="hljs-property">list</span> = state.<span class="hljs-property">list</span>.<span class="hljs-title function_">filter</span>(<span class="hljs-function"><span class="hljs-params">task</span> =&gt;</span> task.<span class="hljs-property">id</span> !== action.<span class="hljs-property">payload</span>)<br>   &#125;<br>&#125;<br><br><span class="hljs-comment">// 导出删除action函数</span><br><span class="hljs-comment">// 导出action函数</span><br><span class="hljs-keyword">const</span> &#123; delTask &#125; = taskStore.<span class="hljs-property">actions</span><br><span class="hljs-keyword">export</span> &#123; delTask &#125;<br><span class="hljs-comment">// 导入生成dispatch方法的hook</span><br><span class="hljs-keyword">import</span> &#123; useDispatch &#125; <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;react-redux&#x27;</span><br><br><span class="hljs-comment">// 得到dispatch方法</span><br><span class="hljs-keyword">const</span> dispatch = <span class="hljs-title function_">useDispatch</span>()<br><br><span class="hljs-comment">// 通过dispatch函数调用action并传入id</span><br>&lt;button<br>  className=<span class="hljs-string">&quot;destroy&quot;</span><br>  onClick=&#123;<span class="hljs-function">() =&gt;</span> <span class="hljs-title function_">dispatch</span>(<span class="hljs-title function_">delTask</span>(task.<span class="hljs-property">id</span>))&#125;&gt;<br>&lt;/button&gt;<br></code></pre></td></tr></table></figure>

<h2 id="4-切换单选状态"><a href="#4-切换单选状态" class="headerlink" title="4. 切换单选状态"></a>4. 切换单选状态</h2><p>实现步骤：</p>
<ol>
<li>在reducers选项中创建切换状态的函数，内部通过传入的id找到要修改的项 进行取反</li>
<li>组件中通过dispatch函数触发并传入id</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-attr">reducers</span>:&#123;<br>  toggleTask (state, action) &#123;<br>    <span class="hljs-keyword">const</span> item = state.<span class="hljs-property">list</span>.<span class="hljs-title function_">find</span>(<span class="hljs-function"><span class="hljs-params">task</span> =&gt;</span> task.<span class="hljs-property">id</span> === action.<span class="hljs-property">payload</span>)<br>    item.<span class="hljs-property">done</span> = !item.<span class="hljs-property">done</span><br>  &#125;<br>&#125;<br><br><span class="hljs-comment">// 解构导出</span><br><span class="hljs-keyword">const</span> &#123; toggleTask &#125; = taskStore.<span class="hljs-property">actions</span><br><br><span class="hljs-comment">// 导出action函数</span><br><span class="hljs-keyword">export</span> &#123; toggleTask &#125;<br>&lt;input<br>  className=<span class="hljs-string">&quot;toggle&quot;</span><br>  type=<span class="hljs-string">&quot;checkbox&quot;</span><br>  checked=&#123;task.<span class="hljs-property">done</span>&#125;<br>  onChange=&#123;<span class="hljs-function">() =&gt;</span> <span class="hljs-title function_">dispatch</span>(<span class="hljs-title function_">toggleTask</span>(task.<span class="hljs-property">id</span>))&#125;<br>/&gt;<br></code></pre></td></tr></table></figure>

<h2 id="5-切换全选状态"><a href="#5-切换全选状态" class="headerlink" title="5. 切换全选状态"></a>5. 切换全选状态</h2><p>实现思路：</p>
<ol>
<li>全选其实就是遍历数组中的所有项把每一项的done字段都改成true</li>
<li>反选其实就是遍历数组中的所有项把每一项的done字段都改成false</li>
<li>总之，done字段的值始终和当前全选框的状态决定</li>
</ol>
<p>实现步骤：</p>
<ol>
<li>在store中的reducers函数中定义修改数据的action函数控制done字段的变化</li>
<li>导出相应的action函数 供组件使用</li>
<li>组件中通过 checked属性控制是否全选的UI显示，在change事件中触发action</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-attr">reducers</span>:&#123;<br>  <span class="hljs-comment">// 全选</span><br>  <span class="hljs-title function_">allCheck</span>(<span class="hljs-params">state, action</span>)&#123;<br>    state.<span class="hljs-property">list</span>.<span class="hljs-title function_">forEach</span>(<span class="hljs-function"><span class="hljs-params">item</span>=&gt;</span>item.<span class="hljs-property">done</span> = action.<span class="hljs-property">payload</span>)<br>  &#125;<br>&#125;<br><br><span class="hljs-comment">// 导出action函数</span><br><span class="hljs-keyword">const</span> &#123; allCheck &#125; = taskStore.<span class="hljs-property">actions</span><br><span class="hljs-keyword">export</span> &#123; allCheck &#125;<br></code></pre></td></tr></table></figure>



<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs jsx">&lt;input<br>  id=<span class="hljs-string">&quot;toggle-all&quot;</span><br>  className=<span class="hljs-string">&quot;toggle-all&quot;</span><br>  type=<span class="hljs-string">&quot;checkbox&quot;</span><br>  checked=&#123;list.<span class="hljs-title function_">every</span>(<span class="hljs-function">(<span class="hljs-params">task</span>) =&gt;</span> task.<span class="hljs-property">done</span>)&#125;<br>  onChange=&#123;<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> <span class="hljs-title function_">dispatch</span>(<span class="hljs-title function_">allCheck</span>(e.<span class="hljs-property">target</span>.<span class="hljs-property">checked</span>))&#125;<br>/&gt;<br></code></pre></td></tr></table></figure>

<h2 id="6-新增实现"><a href="#6-新增实现" class="headerlink" title="6. 新增实现"></a>6. 新增实现</h2><p>要求: 输入框中输入内容，用户在回车时可以实现添加功能</p>
<p>实现思路和步骤</p>
<ol>
<li>在redux中定义新增的方法 addTask</li>
<li>在组件中通过受控的方式 记录输入框中的数据</li>
<li>keyUp事件中判断当前是否点击的是enter[keyCode为13]  如果是通过dispatch执行修改</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><code class="hljs javascript"><span class="hljs-comment">// 新增: 按照list中item的对象结构 传入一个新的对象 push到数组中</span><br><span class="hljs-attr">reducer</span>:&#123;<br>   addTask (state, action) &#123;<br>      state.<span class="hljs-property">taskList</span>.<span class="hljs-title function_">push</span>(action.<span class="hljs-property">payload</span>)<br>   &#125;<br>&#125;<br><span class="hljs-comment">// 1. 受控的方式存入用户输入数据  </span><br><span class="hljs-comment">// 2.keyUp 判断点击的是enter dispatch触发修改数据的函数</span><br><span class="hljs-keyword">const</span> [keyword, setKeyword] = <span class="hljs-title function_">useState</span>(<span class="hljs-string">&#x27;&#x27;</span>)<br><span class="hljs-keyword">const</span> <span class="hljs-title function_">onChange</span> = (<span class="hljs-params">e</span>) =&gt; &#123;<br>  <span class="hljs-title function_">setKeyword</span>(e.<span class="hljs-property">target</span>.<span class="hljs-property">value</span>)<br>&#125;<br><span class="hljs-keyword">const</span> <span class="hljs-title function_">onKeyUp</span> = (<span class="hljs-params">e</span>) =&gt; &#123;<br>  <span class="hljs-keyword">if</span> (e.<span class="hljs-property">keyCode</span> === <span class="hljs-number">13</span>) &#123;<br>    <span class="hljs-title function_">dispatch</span>(<br>      <span class="hljs-title function_">addTask</span>(&#123;<br>        <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>,<br>        <span class="hljs-attr">name</span>: keyword,<br>        <span class="hljs-attr">isDone</span>: <span class="hljs-literal">false</span>,<br>      &#125;)<br>    )<br>    <span class="hljs-title function_">setKeyword</span>(<span class="hljs-string">&#x27;&#x27;</span>)<br>  &#125;<br>&#125;<br><br>&lt;input<br>  className=<span class="hljs-string">&quot;new-todo&quot;</span><br>  autoFocus<br>  autoComplete=<span class="hljs-string">&quot;off&quot;</span><br>  placeholder=<span class="hljs-string">&quot;What needs to be done?&quot;</span><br>  value=&#123;keyword&#125;<br>  onChange=&#123;onChange&#125;<br>  onKeyUp=&#123;onKeyUp&#125;<br>/&gt;<br></code></pre></td></tr></table></figure>



<h1 id="美团小案例"><a href="#美团小案例" class="headerlink" title="美团小案例"></a>美团小案例</h1><h2 id="1-准备环境"><a href="#1-准备环境" class="headerlink" title="1. 准备环境"></a>1. 准备环境</h2><figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs bash"><span class="hljs-comment"># 克隆项目到本地</span><br>git <span class="hljs-built_in">clone</span> http://git.itcast.cn/heimaqianduan/redux-meituan.git<br><br><span class="hljs-comment"># 安装所有依赖</span><br>npm i<br><br><span class="hljs-comment"># 启动mock服务</span><br>npm run serve<br><br><span class="hljs-comment"># 启动前端服务</span><br>npm run start<br></code></pre></td></tr></table></figure>
                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/React/" class="category-chain-item">React</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/React/">#React</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>04.Redux</div>
      <div>http://example.com/2023/06/04/编程语言/React/04.Redux/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>深海火锅店</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2023年6月4日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/06/05/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/React/05.Zustand/" title="05.Zustand">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">05.Zustand</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2023/06/03/%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/React/02.ReactRouter/" title="02.ReactRouter">
                        <span class="hidden-mobile">02.ReactRouter</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="margin-left: -1rem">
    <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>
  </div>
</div>





  



  



  



  



  







    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.0/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.18.2/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  
<script src="//cdn.jsdelivr.net/gh/EmoryHuang/BlogBeautify@1.1/DynamicRibbon.min.js"></script>



<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
